package javase.jmx.timer;

import java.util.Date;

import javax.management.timer.Timer;

public class TimerAgent {
	private static final int FIRST_PERIOD = 1000;
	private static final int SECOND_PERIOD = 500;
	private static final int FIRST_NUMBER_OF_OCCURENCES = 2;
	private static final int SECOND_NUMBER_OF_OCCURENCES = 2;
	
	public static void main(String[] args) throws Exception {
		Timer timer = new Timer();
		System.out.println("Started timer and waiting ..."); 
		timer.start();
		timer.setSendPastNotifications(true);
		TimerNotificationListener unfilteredListener = getUnfilteredNotificationListener(timer);
		TimerNotificationListener filtered = getFilteredNotificationListener(timer);
		registerFirstNotification(timer);
		registerSecondNotification(timer);
	    Thread.sleep(getSleepTimeout());
	    System.out.println("Stopping timer");
	    timer.stop();
	    printMessageCount(unfilteredListener);
	    printMessageCount(filtered);
	}

	private static void printMessageCount(TimerNotificationListener listener) {
		System.out.println("Message count in " + listener.getName() + ": " + listener.getCount());
	}

	private static TimerNotificationListener getUnfilteredNotificationListener(Timer timer) {
		TimerNotificationListener listener = new TimerNotificationListener("Unfiltered Listener");
		timer.addNotificationListener(listener, null, null);
		return listener;
	}

	private static void registerFirstNotification(Timer timer) {
		String type = "com.notification.first";
		String message = "message text";
		Integer userData = new Integer(47);
		timer.addNotification(type, message, userData, new Date(), FIRST_PERIOD, FIRST_NUMBER_OF_OCCURENCES);
	}
	
	private static TimerNotificationListener getFilteredNotificationListener(Timer timer) {
		TimerNotificationFilter filter = new TimerNotificationFilter();
		TimerNotificationListener listener = new TimerNotificationListener("Filtered Listener  ");
		timer.addNotificationListener(listener, filter, null);
		return listener;
	}

	private static void registerSecondNotification(Timer timer) {
		String message = "message";
		Integer userData = new Integer(11);
		timer.addNotification(TimerNotificationFilter.ALLOWED_NOTIFICATION_TYPE, 
				message, userData, new Date(), SECOND_PERIOD, SECOND_NUMBER_OF_OCCURENCES);
	}
	
	private static int getSleepTimeout() {
		return 4000;
	}
}
